package cn.zhaoyuening.zshop4j.manager.web;

import cn.zhaoyuening.zshop4j.common.bean.FileUploadBean;
import cn.zhaoyuening.zshop4j.common.utils.JsonUtils;
import cn.zhaoyuening.zshop4j.manager.service.FileResourcesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Created by Zhao on 2017/4/8.
 */
@Controller
public class FileResourcesController {
    @Autowired
    private FileResourcesService fileResourcesService;

    @RequestMapping(value = "images", method = RequestMethod.POST,produces = "text/plain;charset=utf8")
    @ResponseBody
    public String uploadImage(@RequestParam("uploadFile")MultipartFile image) throws IOException {
        if (image.isEmpty())
            return null;
        String imageUrl = fileResourcesService.uploadImage(image.getBytes(), image.getOriginalFilename());
        FileUploadBean bean = new FileUploadBean();
        bean.setUrl(imageUrl);

        if (imageUrl != null){
            bean.setError(true);
        }else {
            bean.setError(false);
        }

        String jsonStr = JsonUtils.objectToJson(bean);
        return jsonStr;
    }
}
